<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>基础菜单 - Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.8.11/layui/css/layui.css">
    <link rel="stylesheet" href="../../../css/serial.css">
    <style>
        .layui-layer-loading .layui-layer-content {
            width: 100%;
        }

        /* .layui-table-cell.laytable-cell-3-0-5 {
            overflow: unset;
        } */

        .layui-unselect.layui-form-select input {
            width: 100%;
        }

        .layui-input-block {
            width: 28vw;
        }

        .layui-form-selectup dl {
            top: auto;
            bottom: auto;
        }


        .layui-table-body::-webkit-scrollbar {
            height: 10px;
        }

        .layui-table-body::-webkit-scrollbar-thumb {
            width: 5px;
            border-radius: 5px;
            -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.11);
            /* background: #5d7cd7; */
        }

        .layui-form-label {
            white-space: nowrap;
        }

        .layui-table-body::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
            border-radius: 5px;
            background: #ffffff;
        }

        .overflowC {
            overflow: unset !important
        }
    </style>
</head>

<body class="layui-bg-gray">
    <div class="layui-row ">
        <div class="layui-panel layui-col-md2" style=" margin: 16px;">
            <div class="left-menu">
                <ul class="layui-menu" id="demo-menu">
                </ul>
            </div>
        </div>
        <div class="layui-panel layui-col-md9 layui-form" style=" margin: 16px;" lay-filter="demo-form">
            <!-- 给容器追加 class="layui-form-pane"，即可显示为方框风格 -->
            <form id="right-form">
            </form>
            <form id="Serial_Slave">
            </form>
        </div>
    </div>
    <!-- <script src="../lib/layui-v2.8.11/layui/layui.js"></script> -->
    <!-- <script src="../lib/layui-v2.8.11/layui/layui.js" charset="utf-8"></script> -->
    <!-- <script src="/lib/layui-v2.8.11/layui/layui.js" charset="utf-8"></script> -->
    <script src="../js/api.js" charset="utf-8"></script>
    <script src="../js/ajaxRequest.js" charset="utf-8"></script>
    <script type="text/html" id="templet-demo-theads-tool">
        <div class="layui-clear-space">
          <a class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs"  lay-event="detailSave"> 保存</a>
          <a class="layui-btn layui-btn-primary layui-border-red layui-btn-xs" lay-event="delete">删除</a>
        </div>
    </script>
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
          <button class="layui-btn layui-btn-sm  layui-btn-primary layui-border-green" lay-event="add">新增</button>  
          <button class="layui-btn layui-btn-sm layui-bg-red" lay-event="deletes">批量删除</button>       
        </div>
    </script>
    <!-- <script type="text/html" id="dataChange">
        <div class="layui-form"></div>
            <select name="ComName" lay-filter="dataC">
                <option value="0" selected>原始数据</option>
                <option value="1">16位无符号整数</option>                                                   
            </select>        
        </div>
     </script> -->
    <script>
        layui.use(['dropdown', 'layer', 'util', 'form', 'table', 'element', 'upload'], function () {
            var data;
            var dropdown = layui.dropdown;
            var layer = layui.layer;
            var util = layui.util;
            var form = layui.form;
            var table = layui.table;
            var element = layui.element;
            var upload = layui.upload;
            var comType = 1

            form1()
            //获取串口类型
            GetSystemInfo().then(function (responseData) {
                if (responseData.code == 0) {
                    comType = responseData.data.ComType
                }
            })
            function form1() {
                $('#demo-menu').empty();

                //layui.use(['dropdown', 'layer', 'util', 'form', 'table', 'element'], function () {


                // dropdown.close('click(demo-menu)')
                //  sendAjaxRequest('GET', '/Serial/GetSerialInfo', null, function (response) {
                var loadingIndex = layer.load(3, {
                    content: '加载中...', // 自定义加载文本
                    shade: [0.4, '#fff'], // 遮罩透明度
                    time: 5 * 1000,
                });
                GetSerialInfo().then(function (responseData) {
                    layer.close(loadingIndex);
                    data = responseData;
                    //  data = response.data;
                    // 遍历数据，动态生成菜单项
                    var html = '';
                    html += `<li class="layui-menu-item-divider"></li><li class="layui-menu-item-group layui-menu-item-down">
                                <li lay-options="{id:0,ComName:'',Describe:''}"><div class="layui-menu-body-title" style="color: #16B777">新建采集信息</div></li>
                            </li>`
                    // <li ><div class="layui-menu-body-title" style="color: #16B777">采集周期</div></li>

                    data.forEach(function (item) {
                        //                     html += ` <li class="layui-menu-item-divider"></li><li class="layui-menu-item-group layui-menu-item-down" lay-options="{type: 'group'}">
                        //   <div class="layui-menu-body-title">  ${item.ComName == "/dev/ttyS8" ? "COM1" : item.ComName == "/dev/ttyS3" ? "COM2" : item.ComName == "/dev/ttyS7" ? "COM3" :
                        //                             item.ComName == "/dev/ttyS6" ? "COM4" : item.ComName == "/dev/ttyS4" ? "COM5" : item.ComName == "/dev/ttyS5" ? "COM6" :
                        //                                 item.ComName == "/dev/ttyS9" ? "COM7" : item.ComName == "/dev/ttyS2" ? "COM8" : item.ComName}<i class="layui-icon layui-icon-up"></i> </div>`
                        html += ` <li class="layui-menu-item-divider"></li><li class="layui-menu-item-group layui-menu-item-down" lay-options="{type: 'group'}">
      <div class="layui-menu-body-title">  ${item.ComName2}<i class="layui-icon layui-icon-up"></i> </div>`
                        html += '<ul>'
                        html += `<li lay-options="{id: ${item.ID},ComName:'${item.ComName}',Agreement:'${item.Agreement}',BAD:'${item.BAD}'
                    ,ByteMode:'${item.ByteMode}',CHC:'${item.CHC}',DAB:'${item.DAB}',Describe:'${item.Describe}'
                    ,STO:'${item.STO}',TPITV:'${item.TPITV}',Timeout:${item.Timeout},SBTimeout:${item.SBTimeout},RetryCount:${item.RetryCount},Rack:${item.Rack},Slot:${item.Slot},IsErrorBreak:${item.IsErrorBreak},ErrorMoveToFront:${item.ErrorMoveToFront}}"><div class="layui-menu-body-title">属性</div></li>`
                        item.Serial_Slave.forEach(item1 => {
                            html += `<li lay-options="{Serial_Slave_ID: ${item1.ID},Serial_ID: ${item1.Serial_ID},ModbusSlaveID: '${item1.ModbusSlaveID}',Name: '${item1.Name}'
                        ,Agreement:'${item.Agreement}',Describe: '${item1.Describe}',CJ188Type:'${item1.CJ188Type}',CJ188DataIdentifier:'${item1.CJ188DataIdentifier}'
                        ,CJ188UnitType:'${item1.CJ188UnitType}',ModbusType:'${item1.ModbusType}',IsCollect:'${item1.IsCollect}' }"><div class="layui-menu-body-title">${item1.Name}</div></li>`
                        })
                        html += `<li lay-options="{id: 0,Serial_ID: ${item.ID},Agreement:'${item.Agreement}' }"><div class="layui-menu-body-title" style="color: #16B777">新建设备</div></li>`
                        html += '</ul>'
                        html += '</li>'
                    });

                    $('#demo-menu').append(html);


                    // 初始化菜单
                    //  dropdown.init();

                })

                // 点击属性
                dropdown.on('click(demo-menu)', function (options) {
                    //console.log('comType', comType)
                    //console.log('options', options)
                    // if(options.Describe==""||options.Describe==null)
                    var htmlR = '';
                    // 清空右侧表单内容
                    $('#right-form').empty();
                    if (options.title == '属性' || options.title == '新建采集信息') {
                        htmlR += `
                            <div class="layui-card-header"><h3>属性</h3>
                                <span> 
                                   `
                        if (options.title != '新建采集信息') {
                            htmlR += ` <button class="layui-btn  layui-btn-primary layui-border-red " lay-submit  lay-filter="serialdelete">
                                        <i class="layui-icon layui-icon-delete"> </i>  删除
                                    </button> `
                        }
                        /*
                        <label class="layui-form-label">名称</label>
                        <div class="layui-input-block">
                                       <input type="text" name="ComName" autocomplete="off" placeholder="请输入" lay-verify="required"
                                           value='${options.ComName}' class="layui-input">
                                   </div>*/
                        htmlR += `<button class="layui-btn  layui-btn-primary layui-border-green" lay-submit  lay-filter="submit">提交</button>
                                </span>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-card-body">
                                    <h4>应用层协议</h4>
                                    <hr>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label required">协议</label>                                        
                                        <div> 
                                            <select name="Agreement" lay-filter="agreementfilter">
                                                <option value="1"selected>MODBUS RTU</option>
                                                <option value="4">MODBUS TCP</option>
                                                <option value="2">DLT645 RTU</option>
                                                <option value="3">西门子S7 TCP</option>
                                                <option value="5">CJ188 RTU</option>

                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item ">                                      
                                        <div id="ComNameRTU">
                                            <label class="layui-form-label required">串口选择</label>
                                            <select name="ComName">
                                                <option value="${comType == 1 ? "/dev/ttyS8" : "/dev/ttyS1"}" selected>COM1</option>
                                                <option value="${comType == 1 ? "/dev/ttyS3" : "/dev/ttyS2"}">COM2</option>
                                                <option value="${comType == 1 ? "/dev/ttyS7" : "/dev/ttyS3"}">COM3</option>
                                                <option value="${comType == 1 ? "/dev/ttyS6" : "/dev/ttyS4"}">COM4</option>
                                                ${comType == 1 ? `<option value="/dev/ttyS4">COM5</option>` : ""}
                                                ${comType == 1 ? `<option value="/dev/ttyS5">COM6</option>` : ""}
                                                ${comType == 1 ? `<option value="/dev/ttyS9">COM7</option>` : ""}
                                                ${comType == 1 ? `<option value="/dev/ttyS2">COM8</option>` : ""}
                                            </select>
                                        </div>
                                        <div id="ComNameTCP" style="display: flex;" class="layui-hide">
                                                <label class="layui-form-label required">TCP/IP地址</label>
                                                <input type="text" name="ComNameTCP" autocomplete="off" placeholder="请输入" 
                                                value='${options.ComName}' class="layui-input inputFlex">                                            
                                        </div>
                                    </div>
                                    <div class="layui-form-item flexM">                                          
                                        <div id="Rack" style="display: flex;" class="layui-hide">
                                            <label class="layui-form-label required">Rack</label>
                                            <input type="number" min="0" lay-affix="number"  name="Rack" autocomplete="off" placeholder="请输入"  onkeyup="value=value.replace(/[^\\d]/g,'')" 
                                            value='${options.Rack}' class="layui-input inputFlex">                                 
                                        </div>
                                    </div>
                                    <div class="layui-form-item flexM">
                                        <div id="Slot" style="display: flex;" class="layui-hide">
                                            <label class="layui-form-label required">Slot</label>
                                            <input type="number" min="0" lay-affix="number"  name="Slot" autocomplete="off" placeholder="请输入"  onkeyup="value=value.replace(/[^\\d]/g,'')" 
                                            value='${options.Slot}' class="layui-input inputFlex"> 
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-card-body">
                                    <h4>传输层协议</h4>
                                    <hr>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label required">波特率</label>
                                        <div id="BAD">
                                            <select name="BAD">
                                                <option value="300">300</option>
                                                <option value="600">600</option>
                                                <option value="1200">1200</option>
                                                <option value="2400">2400</option>
                                                <option value="4800">4800</option>
                                                <option value="9600"selected>9600</option>
                                                <option value="19200">19200</option>
                                                <option value="38400">38400</option>
                                                <option value="57600">57600</option>
                                                <option value="115200">115200</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label required">数据位</label>
                                        <div id="DAB">
                                            <select name="DAB" >
                                                    <option value="8"selected>8位</option>
                                                    <option value="7">7位</option>
                                                    <option value="6">6位</option>
                                                    <option value="5">5位</option>
                                                    <option value="4">4位</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label required">校验方式</label>
                                         <div id="CHC">
                                            <select name="CHC" >
                                                    <option value="N"selected>无校验</option>
                                                    <option value="E">偶校验</option>
                                                    <option value="O">奇校验</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                            <label class="layui-form-label required">停止位</label>
                                            <div id="STO">
                                                <select name="STO">
                                                    <option value="1"selected>1</option>
                                                    <option value="2">2</option>
                                                </select>
                                            </div>
                                    </div>
                                </div>
                            </div>`
                        htmlR += `   
                        <div class="layui-col-md12">                           
                            <div class="layui-card-body">
                                <h4>连接配置</h4>  
                                <hr>
                                <li class="layui-menu  layui-menu-item-divider"></li>                               
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label">描述</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="Describe" autocomplete="off" placeholder="请输入" 
                                            value='${options.Describe}' class="layui-input">
                                        <input name="ID" style="display:none">
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label required">采集周期(秒)</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="1" name="TPITV" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"   value='${options.TPITV == "" ? 60 : options.TPITV}' >                                        
                                          
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label required">超时时间(秒)</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="1" max="60" name="Timeout" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"   value='${options.Timeout == "" ? 1 : options.Timeout}' >                                        
                                           
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label required">重试次数</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="1" max="60" name="RetryCount" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"   value='${options.RetryCount == "" ? 1 : options.RetryCount}' >                                        
                                          
                                    </div>
                                </div>                                
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label required">每条指令间隔(秒)</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="0" max="60" name="SBTimeout" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"  value='${options.SBTimeout == "" ? 0 : options.SBTimeout}' >  
                                    </div>
                                </div>
                                <div id="IsErrorBreak"  class="layui-form-item topinput ">
                                    <label class="layui-form-label">采集错误跳过</label>
                                    <div class="layui-input-block">
                                        <input type="checkbox" name="IsErrorBreak" lay-filter="IsErrorBreak" title="开启|关闭" lay-skin="switch">
                                    </div>
                                </div>
                                <div id="ErrorMoveToFront"  class="layui-form-item topinput">
                                    <label class="layui-form-label">错误提前采集</label>
                                    <div class="layui-input-block">
                                        <input type="checkbox" name="ErrorMoveToFront" lay-filter="ErrorMoveToFront" title="开启|关闭" lay-skin="switch">
                                    </div>
                                </div>
                            </div>
                        </div>`
                        // <div class="layui-form-item">
                        //             <label class="layui-form-label">字节流方式</label>
                        //             <div>
                        //                 <select name="ByteMode" lay-filter="byteModefilter" >
                        //                     <option value="RTU"selected>RTU</option>
                        //                     <option value="TCP">TCP</option>

                        //                 </select>
                        //             </div>
                        //         </div>
                        $('#right-form').append(htmlR);
                        form.render(); // 渲染全部表单
                        // 初始化时给 select 赋值
                        form.val('demo-form', {
                            'BAD': options.BAD == undefined ? "9600" : options.BAD,
                            'DAB': options.DAB == undefined ? "8" : options.DAB,
                            'CHC': options.CHC == undefined ? "N" : options.CHC,
                            'STO': options.STO == undefined ? "1" : options.STO,
                            'ComName': options.ComName == undefined ? "/dev/ttyS8" : options.ComName,
                            'Agreement': options.Agreement == undefined ? "1" : options.Agreement,
                            //'ByteMode': options.ByteMode == undefined ? "RTU" : options.ByteMode,
                            'ID': options.id
                        });
                        if (options.Agreement == "3" || options.Agreement == "4") {
                            ChangeSelectDisabled(true, options.Agreement)
                        } else if (options.Agreement == "1") {
                            ChangeSelectDisabled(false, options.Agreement)
                        }
                        // select 事件
                        form.on('select(agreementfilter)', function (data) {
                            var elem = data.elem; // 获得 select 原始 DOM 对象
                            var value = data.value; // 获得被选中的值
                            var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象
                            //console.log("1", this.innerHTML + ' 的 value: ' + value)
                            if (value == "3" || value == "4") {
                                ChangeSelectDisabled(true, value)
                            } else {
                                ChangeSelectDisabled(false, value)
                            }
                            // layer.msg(this.innerHTML + ' 的 value: ' + value); // this 为当前选中 <option> 元素对象
                        });
                        //console.log("options", options)
                        //采集错误跳过功能 
                        if (options.IsErrorBreak == 1) {
                            $('input[name="IsErrorBreak"]').prop('checked', true)
                        } else {
                            $('input[name="IsErrorBreak"]').prop('checked', false)
                        }
                        if (options.ErrorMoveToFront == 1) {
                            $('input[name="ErrorMoveToFront"]').prop('checked', true)
                        } else {
                            $('input[name="ErrorMoveToFront"]').prop('checked', false)
                        }
                        
                        form.render('checkbox');

                        function ChangeSelectDisabled(b, value) {
                            if (b) { //选中tcp时
                                $('#BAD .layui-input.layui-unselect').attr("disabled", true)
                                $('#DAB .layui-input.layui-unselect').attr("disabled", true)
                                $('#CHC .layui-input.layui-unselect').attr("disabled", true)
                                $('#STO .layui-input.layui-unselect').attr("disabled", true)
                                $("#ComNameRTU").addClass("layui-hide");
                                $("#ComNameTCP").removeClass("layui-hide");
                                $("#IsErrorBreak").addClass("layui-hide");
                                $("#ErrorMoveToFront").addClass("layui-hide");
                                if (value == "3") {
                                    $("#Rack").removeClass("layui-hide");
                                    $("#Slot").removeClass("layui-hide");
                                } else if (value == "4") {
                                    $("#Rack").addClass("layui-hide");
                                    $("#Slot").addClass("layui-hide");
                                    //modbus 显示采集错误跳过功能
                                    $("#IsErrorBreak").removeClass("layui-hide");
                                    $("#ErrorMoveToFront").removeClass("layui-hide");                                    
                                }
                            } else {
                                $('#BAD .layui-input.layui-unselect').removeAttr("disabled")
                                $('#DAB .layui-input.layui-unselect').removeAttr("disabled")
                                $('#CHC .layui-input.layui-unselect').removeAttr("disabled")
                                $('#STO .layui-input.layui-unselect').removeAttr("disabled")
                                $("#ComNameRTU").removeClass("layui-hide");
                                $("#ComNameTCP").addClass("layui-hide");
                                $("#Rack").addClass("layui-hide");
                                $("#Slot").addClass("layui-hide");
                                $("#IsErrorBreak").addClass("layui-hide");
                                $("#ErrorMoveToFront").addClass("layui-hide");                                
                                if (value == "1") {
                                    //modbus 显示采集错误跳过功能
                                    $("#IsErrorBreak").removeClass("layui-hide");
                                    $("#ErrorMoveToFront").removeClass("layui-hide");  
                                }
                            }
                        }
                        // 提交事件
                        form.on('submit(submit)', function (data) {
                            var field = data.field; // 获取表单字段值
                            if (field.Agreement == "3" || field.Agreement == "4") {
                                field.ComName = field.ComNameTCP
                                if (field.ComName.indexOf(":") == -1) {
                                    layer.msg("TCP名称未填写正确，格式为 192.168.1.1:21", {
                                        icon: 2
                                    });
                                    return false;
                                }
                            }
                            if (field.ComName == null || field.ComName == "" || field.ComName == undefined) {
                                if (field.Agreement == "1" || field.Agreement == "2") {
                                    layer.msg("串口未选择", {
                                        icon: 2
                                    });
                                } else if (field.Agreement == "3" || field.Agreement == "4") {
                                    layer.msg("TCP/IP地址未填写", {
                                        icon: 2
                                    });
                                }
                                return false;
                            }
                            if (field.Agreement == "3") {
                                if (field.Rack == null || field.Rack == "" || field.Rack == undefined) {

                                    layer.msg("Rack必填", {
                                        icon: 2
                                    });
                                    return false;
                                }
                                else if (field.Slot == null || field.Slot == "" || field.Slot == undefined) {

                                    layer.msg("Slot必填", {
                                        icon: 2
                                    });
                                    return false;
                                }
                            }
                            field.Rack = parseInt(field.Rack)
                            field.Slot = parseInt(field.Slot)
                            field.TPITV = parseInt(field.TPITV)
                            field.Timeout = parseInt(field.Timeout)
                            field.SBTimeout = parseInt(field.SBTimeout)
                            field.RetryCount = parseInt(field.RetryCount)
                            field.ID = parseInt(field.ID)
                            if (field.TPITV < 0 || field.TPITV == 0) {
                                layer.msg("采集周期必须大于0", {
                                    icon: 2
                                });
                                return false;
                            }
                            if (field.Timeout <= 0 || field.Timeout > 60) {
                                layer.msg("超时时间范围1~60", {
                                    icon: 2
                                });
                                return false;
                            }
                            if (field.SBTimeout < 0 || field.SBTimeout > 60) {
                                layer.msg("每条指令间隔0~60", {
                                    icon: 2
                                });
                                return false;
                            }
                            if (field.RetryCount <= 0 || field.RetryCount > 60) {
                                layer.msg("重试次数范围1~60", {
                                    icon: 2
                                });
                                return false;
                            }

                            field.TPITV = field.TPITV.toString()
                            field.IsErrorBreak = $("[name='IsErrorBreak']").prop('checked') == true ? 1 : 2
                            field.ErrorMoveToFront = $("[name='ErrorMoveToFront']").prop('checked') == true ? 1 : 2 
                            var obj = { serial: field }
                            //console.log("field", field)
                            EditSeria(obj).then(function (responseData1) {
                                if (responseData1.success) {
                                    form1()
                                }
                            })
                            // location.reload();
                            return false; // 阻止默认 form 跳转
                        });
                        //删除串口
                        form.on('submit(serialdelete)', function (data) {
                            layer.confirm('确认删除数据吗', function (index) {
                                const postData = { serialID: parseInt(options.id) };
                                DeleteSeria(postData).then(function (responseData1) {
                                    if (responseData1.success) {
                                        form1()
                                        $('#right-form').empty();
                                    }
                                })
                            });
                            return false; // 阻止默认 form 跳转
                        });
                    }
                    else if (options.Serial_Slave_ID != null && options.Serial_Slave_ID != 0) {
                        form2(options)
                        // if (options.Agreement == 2) {
                        //     console.log('options', options)
                        // }
                    }
                    // else if (options.title == '采集周期') {
                    //     GetTPITV().then(function (responseData) {
                    //         var data = responseData;
                    //         form4(data.data)
                    //     })
                    // }
                    else if (options.title == '新建设备') {
                        form3(options)
                    }
                    // layer.msg(util.escape(JSON.stringify(options)));
                });

                //  dropdown.off('click(demo-menu)');
                // });
                // });
            }

            function form2(options) {
                var serial_Slave_ID = options.Serial_Slave_ID
                var serial_ID = options.Serial_ID
                //点击地址位
                // 遍历数据，动态生成菜单项
                var html = '';
                // data.forEach(function (item) {
                html += `  <div class="layui-card-header"><h3>${options.Name}</h3><span>
                    <button class="layui-btn layui-btn-primary layui-border-red" lay-submit id="buttonDelete" lay-filter="submitdelete"> 
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </button> 
                    <button class="layui-btn layui-btn-primary layui-border-green" lay-submit id="button2" lay-filter="submit2">提交</button></span></div> 
                <div class="layui-tab" lay-filter="tab-hash">
                    <ul class="layui-tab-title">
                        <li class="layui-this" lay-id="0">基本信息</li>
                        <li  ${options.Agreement == "1" || options.Agreement == "4" ? "" : 'style="display: none;"'}  lay-id="1">功能码1</li>
                        <li  ${options.Agreement == "1" || options.Agreement == "4" ? "" : 'style="display: none;"'} lay-id="2">功能码2</li>
                        <li  ${options.Agreement == "1" || options.Agreement == "4" ? "" : 'style="display: none;"'} lay-id="3">功能码3</li>
                        <li  ${options.Agreement == "1" || options.Agreement == "4" ? "" : 'style="display: none;"'} lay-id="4">功能码4</li>
                        <li ${options.Agreement == "2" ? "" : 'style="display: none;"'} lay-id="5">采集</li>
                        <li ${options.Agreement == "3" ? "" : 'style="display: none;"'} lay-id="6">点表</li>
                        <li ${options.Agreement == "5" ? "" : 'style="display: none;"'} lay-id="7">点表</li>
                        <form id="exportForm" action="/Serial/ExportData" method="GET" style="display: none;">
                            <input type="hidden" name="Serial_Slave_ID" value="${options.Serial_Slave_ID}">                           
                        </form>
                        <button class="layui-btn layui-btn-primary layui-border-blue" lay-submit lay-filter="submitExport"> 
                            <i class="layui-icon layui-icon-export"></i> 导出数据
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary layui-border-green" id="uploadBtn"  lay-options="{accept: 'file', exts: 'xlsx'}">
                            <i class="fa fa-cloud-download"></i> 
                            导入数据(新增)
                        </button>
                        <button type="button" style="margin-left: 10px;" class="layui-btn layui-btn-primary layui-border-green" id="uploadBtn2"  lay-options="{accept: 'file', exts: 'xlsx'}">
                            <i class="fa fa-cloud-download"></i> 
                            导入数据(覆盖)
                        </button>
                    </ul>                    
                    <div class="layui-tab-content">
                        <div class="layui-tab-item layui-show overflowC">
                            <div class="layui-card-body">
                                <li class="layui-menu  layui-menu-item-divider"></li>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label required">名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="Name" autocomplete="off" placeholder="请输入" lay-verify="required"
                                            value='${options.Name}' class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label">描述</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="Describe" autocomplete="off" placeholder="请输入" 
                                            value='${options.Describe}' class="layui-input">
                                        <input name="ID" style="display:none">
                                    </div>
                                </div>                              
                                <div class="layui-form-item topinput ${options.Agreement == "5" ? "" : 'layui-hide'}">
                                        <label class="layui-form-label required">仪表类型</label>
                                    <div id="CJ188Type" class="layui-input-block">
                                        <select name="CJ188Type">
                                            <option value="10"selected>冷水水表(标准10)</option>
                                            <option value="20">生活热水水表(标准20)</option>
                                            <option value="25">生活热水水表(亿林25)</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item topinput ${options.Agreement == "5" ? "" : 'layui-hide'}">
                                        <label class="layui-form-label required">数据标识</label>
                                    <div id="CJ188DataIdentifier" class="layui-input-block">
                                        <select name="CJ188DataIdentifier">
                                            <option value="1F90"selected>1F90</option>
                                            <option value="901F">901F</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item topinput ${options.Agreement == "5" ? "" : 'layui-hide'}">
                                        <label class="layui-form-label required">单位位置</label>
                                    <div id="CJ188UnitType" class="layui-input-block">
                                        <select name="CJ188UnitType">
                                            <option value=1>在前</option>
                                            <option value=2 selected>在后面</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label required">设备地址</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="0" max="255" lay-affix="number" name="ModbusSlaveID" autocomplete="off" placeholder="请输入" lay-verify="required|customRange"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"    value=${options.ModbusSlaveID} class="layui-input">
                                        <input name="ID" style="display:none">
                                    </div>
                                </div>
                                <div class="layui-form-item topinput ${options.Agreement == "1" ? "" : 'layui-hide'}">
                                        <label class="layui-form-label ">采集类型</label>
                                    <div id="ModbusType" class="layui-input-block">
                                        <select name="ModbusType">
                                            <option value=1 selected>单点采集</option>
                                            <option value=2 >整帧采集</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                        <label class="layui-form-label required">是否采集</label>
                                    <div id="IsCollect" class="layui-input-block">
                                        <select name="IsCollect">
                                            <option value=1 selected>采集</option>
                                            <option value=2 >不采集</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>                                
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail1"></table></div>
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail2"></table></div>
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail3" lay-filter="serialSlaveDetail3"></table></div>
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail4"></table></div>
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail5"></table></div>
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail6"></table></div>
                        <div class="layui-tab-item"><table class="layui-hide" id="serialSlaveDetail7"></table></div>
                    </div>
                  </div>`
                // });
                $('#right-form').append(html);
                form.render();
                // 自定义验证规则
                form.verify({
                    customRange: function (value, item) {
                        if (options.Agreement == "1" || options.Agreement == "4") {
                            if (value < 0 || value > 255) {
                                return '请输入0到255之间的数字';
                            }
                        }
                    }
                });
                // 已知数据渲染
                var dataList1 = []
                var dataList2 = []
                var dataList3 = []
                var dataList4 = []
                var dataList5 = []
                var dataList6 = []
                var dataList7 = []
                var cols = [[ //标题栏
                    { checkbox: true, fixed: true },
                    { field: 'ID', title: 'ID', width: 20, sort: true },
                    { field: 'CollectName', title: '采集点名', width: 200 },
                    { field: 'Name', title: '变量名', width: 150, edit: 'text' },
                    //{ field: 'Describe', title: '变量描述', width: 150, edit: 'text' },
                    { field: 'CollectAddressID', title: '寄存器地址', width: 100, edit: 'text' },
                    { field: 'Formula', title: '表达式', width: 100, edit: 'text' },
                    // {
                    //     title: '值类型', width: 200, style: 'overflow: unset;',//height:100%
                    //     //templet: '#dataChange'
                    //     templet: function (d) {
                    //         return `
                    //     <div class="layui-form"></div>
                    //         <select id="collectDataSelect`+ d.ID + `" lay-options="${d.ID}"  lay-filter="dataC">
                    //             <option value="0" selected>原始数据</option>
                    //             <option value="1">10进制无符号整数</option>                                                   
                    //         </select>        
                    //      </div>`;
                    //     }
                    // },
                    { field: 'Value3', title: '原始数据', width: 100, templet: '<div><span style="color:red" id="collectData{{=d.ID}}">{{=d.Value3}}</span></div>' },
                    {
                        field: 'ValueType', title: '数据类型<i class="layui-icon layui-icon-tips layui-font-14" lay-event="valueType-tips" title="点击查看对应接收公式" style="margin-left: 5px;"></i>', width: 180, style: 'overflow: unset;',//height:100%
                        //templet: '#dataChange'
                        templet: function (d) {
                            return `
                        <div class="layui-form"></div>
                            <select id="ValueType`+ d.ID + `" sid=${d.ID} type=${d.Type} lay-filter="modbusValueType">                            
                                ${(d.Type == 1 || d.Type == 2) ? `<option value="1" ${d.ValueType === 1 ? 'selected' : ''}>位读取</option>` : ""}
                                
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="4" ${d.ValueType === 4 ? 'selected' : ''}>16位无符号</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="3" ${d.ValueType === 3 ? 'selected' : ''}>16位有符号</option>` : ""}
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="5" ${d.ValueType === 5 ? 'selected' : ''}>32位有符号整型</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="6" ${d.ValueType === 6 ? 'selected' : ''}>32位无符号整型</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="11" ${d.ValueType === 11 ? 'selected' : ''}>32位无符号整型-高低位转换</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="12" ${d.ValueType === 12 ? 'selected' : ''}>48位-特殊</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="7" ${d.ValueType === 7 ? 'selected' : ''}>64位有符号整型</option>` : ""}  
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="8" ${d.ValueType === 8 ? 'selected' : ''}>64位无符号整型</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="9" ${d.ValueType === 9 ? 'selected' : ''}>32位浮点数</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="10" ${d.ValueType === 10 ? 'selected' : ''}>64位浮点数</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2) ? `<option value="-1" ${d.ValueType === -1 ? 'selected' : ''}>表达式</option>` : ""}                                          
                            </select>        
                         </div>`;
                        }
                    },
                    {
                        field: 'ValueStructure', title: '数据结构', width: 120, style: 'overflow: unset;',//height:100%
                        //templet: '#dataChange'
                        templet: function (d) {
                            return `
                        <div class="layui-form"></div>
                            <select id="ValueStructure`+ d.ID + `">
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 3 || d.ValueType === 4 || d.ValueType == null)) ? `<option value="1" ${d.ValueStructure === 1 ? 'selected' : ''}>AB</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 3 || d.ValueType === 4 || d.ValueType == null)) ? `<option value="2" ${d.ValueStructure === 2 ? 'selected' : ''}>BA</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 5 || d.ValueType === 6)) ? `<option value="3" ${d.ValueStructure === 3 ? 'selected' : ''}>ABCD</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 5 || d.ValueType === 6)) ? `<option value="4" ${d.ValueStructure === 4 ? 'selected' : ''}>BADC</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 5 || d.ValueType === 6)) ? `<option value="5" ${d.ValueStructure === 5 ? 'selected' : ''}>CDAB</option>` : ""} 
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 5 || d.ValueType === 6)) ? `<option value="6" ${d.ValueStructure === 6 ? 'selected' : ''}>DCBA</option>` : ""}   
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 12 || d.ValueType === 7 || d.ValueType === 8)) ? `<option value="7" ${d.ValueStructure === 7 ? 'selected' : ''}>低字节在后</option>` : ""}  
                                ${(d.Type != 1 && d.Type != 2 && (d.ValueType === 12 || d.ValueType === 7 || d.ValueType === 8)) ? `<option value="8" ${d.ValueStructure === 8 ? 'selected' : ''}>低字节在前</option>` : ""}                        
                            </select>        
                         </div>`;
                        }
                    },
                    { field: 'Value2', title: '对应数据', width: 100, templet: '<div><span style="color:red" id="collectData2_{{=d.ID}}">{{=d.Value2}}</span></div>' },
                    { field: 'CreateTime', title: '采集时间', width: 170, templet: '<div><span style="color:red" id="collectDataTime{{=d.ID}}">{{=d.CreateTime}}</span></div>' },
                    { fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#templet-demo-theads-tool' }
                ]]
                var colsDLT645 = [[ //标题栏
                    //{checkbox: true, fixed: true},
                    { field: 'ID', title: 'ID', width: 20, sort: true },
                    { field: 'CollectName', title: '采集点名', width: 200 },
                    { field: 'Name', title: '变量名', width: 150, edit: 'text' },
                    { field: 'Describe', title: '变量描述', edit: 'text' },
                    { field: 'DI3', title: 'DI3', width: 50, edit: 'text' },
                    { field: 'DI2', title: 'DI2', width: 50, edit: 'text' },
                    { field: 'DI1', title: 'DI1', width: 50, edit: 'text' },
                    { field: 'DI0', title: 'DI0', width: 50, edit: 'text' },
                    { field: 'Value3', title: '原始数据', width: 80, templet: '<div><span style="color:red" id="collectData{{=d.ID}}">{{=d.Value3}}</span></div>' },
                    { field: 'Value2', title: '真实数据(不带单位)', width: 120, templet: '<div><span style="color:red" id="collectData2_{{=d.ID}}">{{=d.Value2}}</span></div>' },
                    { field: 'CreateTime', title: '采集时间', width: 170, templet: '<div><span style="color:red" id="collectDataTime{{=d.ID}}">{{=d.CreateTime}}</span></div>' },
                    { fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#templet-demo-theads-tool' }
                ]]
                var siemensS7 = [[ //标题栏
                    //{checkbox: true, fixed: true},
                    { field: 'ID', title: 'ID', width: 20, sort: true },
                    { field: 'CollectName', title: '采集点名', width: 200 },
                    { field: 'Name', title: '变量名', width: 100, edit: 'text' },
                    { field: 'Describe', title: '变量描述', edit: 'text' },
                    {
                        field: 'SiemensType', title: '通道类型', width: 100, style: 'overflow: unset;',//height:100%
                        //templet: '#dataChange'
                        templet: function (d) {
                            return `
                        <div class="layui-form"></div>
                            <select id="SiemensType`+ d.ID + `">                    
                                <option value="1" ${d.SiemensType === 1 ? 'selected' : ''}>I</option>
                                <option value="2" ${d.SiemensType === 2 ? 'selected' : ''}>Q</option>
                                <option value="3" ${d.SiemensType === 3 ? 'selected' : ''}>M</option>
                                <option value="4" ${d.SiemensType === 4 ? 'selected' : ''}>DB</option>                                                                            
                            </select>        
                         </div>`;
                        }
                    },
                    { field: 'SiemensAdress', title: '地址', width: 60, edit: 'text' },
                    { field: 'Value3', title: '原始数据', width: 100, templet: '<div><span style="color:red" id="collectData{{=d.ID}}">{{=d.Value3}}</span></div>' },
                    {
                        field: 'ValueType', title: '数据类型<i class="layui-icon layui-icon-tips layui-font-14" lay-event="valueType-tips" title="点击查看对应接收公式" style="margin-left: 5px;"></i>', width: 180, style: 'overflow: unset;',//height:100%
                        //templet: '#dataChange'
                        templet: function (d) {
                            return `
                        <div class="layui-form"></div>
                        <select id="ValueType`+ d.ID + `">                            
                                <option value="1" ${d.ValueType === 1 ? 'selected' : ''}>位读取</option>
                                <option value="2" ${d.ValueType === 2 ? 'selected' : ''}>8位无符号</option>
                                <option value="3" ${d.ValueType === 3 ? 'selected' : ''}>16位有符号</option>
                                <option value="4" ${d.ValueType === 4 ? 'selected' : ''}>16位无符号</option>
                                <option value="5" ${d.ValueType === 5 ? 'selected' : ''}>32位有符号整型</option>
                                <option value="6" ${d.ValueType === 6 ? 'selected' : ''}>32位无符号整型</option>
                                <option value="7" ${d.ValueType === 7 ? 'selected' : ''}>64位有符号整型</option>
                                <option value="8" ${d.ValueType === 8 ? 'selected' : ''}>64位无符号整型</option>
                                <option value="9" ${d.ValueType === 9 ? 'selected' : ''}>32位浮点数</option>
                                <option value="10" ${d.ValueType === 10 ? 'selected' : ''}>64位浮点数</option>                                                  
                            </select>        
                         </div>`;
                        }
                    },
                    { field: 'Value2', title: '对应数据', width: 100, templet: '<div><span style="color:red" id="collectData2_{{=d.ID}}">{{=d.Value2}}</span></div>' },
                    { field: 'CreateTime', title: '采集时间', width: 170, templet: '<div><span style="color:red" id="collectDataTime{{=d.ID}}">{{=d.CreateTime}}</span></div>' },
                    { fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#templet-demo-theads-tool' }
                ]]
                var cj188 = [[ //标题栏
                    //{checkbox: true, fixed: true},
                    { field: 'ID', title: 'ID', width: 20, sort: true },
                    { field: 'CollectName', title: '采集点名', width: 200 },
                    { field: 'Name', title: '变量名', width: 80, edit: 'text' },
                    { field: 'Describe', title: '变量描述', edit: 'text' },
                    { field: 'CJ188DecimalPointOffset', title: '小数点偏移位数', width: 100, edit: 'text' },
                    {
                        field: 'CJ188CType', title: '采集类型', width: 160, style: 'overflow: unset;',//height:100%
                        //templet: '#dataChange'
                        templet: function (d) {
                            return `
                        <div class="layui-form"></div>
                            <select id="CJ188CType`+ d.ID + `"> 
                                ${options.CJ188Type === "10" ? `<option value=1 ${d.CJ188CType === 1 ? 'selected' : ''} >累计用量(冷水水表)</option>` : ""} 
                                ${options.CJ188Type === "10" ? `<option value=2 ${d.CJ188CType === 2 ? 'selected' : ''} >本月用量(冷水水表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=3 ${d.CJ188CType === 3 ? 'selected' : ''} >结算日热量(热量表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=4 ${d.CJ188CType === 4 ? 'selected' : ''} >当前热量(热量表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=5 ${d.CJ188CType === 5 ? 'selected' : ''} >热功率(热量表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=6 ${d.CJ188CType === 6 ? 'selected' : ''} >瞬时热量(热量表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=7 ${d.CJ188CType === 7 ? 'selected' : ''} >当前累计流量(热量表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=8 ${d.CJ188CType === 8 ? 'selected' : ''} >供水温度(热量表)</option>` : ""}
                                ${options.CJ188Type === "20" || options.CJ188Type === "25" ? `<option value=9 ${d.CJ188CType === 9 ? 'selected' : ''} >回水温度(热量表)</option>` : ""}
                            </select>        
                         </div>`
                        }
                    },
                    { field: 'Value3', title: '原始数据', width: 100, templet: '<div><span style="color:red" id="collectData{{=d.ID}}">{{=d.Value3}}</span></div>' },
                    {
                        field: 'ValueType', title: '数据类型<i class="layui-icon layui-icon-tips layui-font-14" lay-event="valueType-tips" title="点击查看对应接收公式" style="margin-left: 5px;"></i>', width: 160, style: 'overflow: unset;',//height:100%
                        //templet: '#dataChange'
                        templet: function (d) {
                            return `
                        <div class="layui-form"></div>
                        <select id="ValueType`+ d.ID + `"> 
                                <option value="9" selected >32位浮点数</option>                                                
                            </select>        
                         </div>`;
                        }
                    },
                    { field: 'Value2', title: '对应数据', width: 100, templet: '<div><span style="color:red" id="collectData2_{{=d.ID}}">{{=d.Value2}}</span></div>' },
                    { field: 'CreateTime', title: '采集时间', width: 170, templet: '<div><span style="color:red" id="collectDataTime{{=d.ID}}">{{=d.CreateTime}}</span></div>' },
                    { fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#templet-demo-theads-tool' }
                ]]
                function processData(data, type, dataList) {
                    // console.log('data', data)
                    data.forEach(function (item) {
                        item.Serial_Slave.forEach(function (item1) {
                            item1.Serial_Slave_Detail.forEach(function (item2) {
                                if (item.ID == options.Serial_ID && item1.ID == options.Serial_Slave_ID) {
                                    if (item2.Type === type) {
                                        dataList.push(item2);
                                    }
                                }
                            });
                        });
                    });
                    // console.log('dataList', dataList)
                }
                processData(data, 1, dataList1);
                processData(data, 2, dataList2);
                processData(data, 3, dataList3);
                processData(data, 4, dataList4);
                processData(data, 0, dataList5);
                processData(data, 10, dataList6);
                processData(data, 11, dataList7);
                var options1 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail1',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: cols,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList1,
                    page: false, // 是否显示分页
                }
                var options2 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail2',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: cols,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList2,
                    page: false, // 是否显示分页
                }
                var options3 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail3',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: cols,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList3,
                    page: false, // 是否显示分页
                }
                var options4 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail4',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: cols,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList4,
                    page: false, // 是否显示分页
                }
                //DLT645 RTU
                var options5 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail5',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: colsDLT645,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList5,
                    page: false, // 是否显示分页
                }
                //西门子S7
                var options6 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail6',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: siemensS7,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList6,
                    page: false, // 是否显示分页
                }
                //cj188
                var options7 = {
                    toolbar: '#toolbarDemo',
                    elem: '#serialSlaveDetail7',
                    css: [
                        // 对开启了编辑的单元格追加样式
                        '.layui-table-view td[data-edit]{color: #16B777;}'
                    ].join(''),
                    cols: cj188,
                    lineStyle: 'height: 50px;',
                    height: 500,
                    data: dataList7,
                    page: false, // 是否显示分页
                }
                table.on('colTool(serialSlaveDetail1)', function (obj) {
                    handleColTool(obj);
                });
                table.on('colTool(serialSlaveDetail2)', function (obj) {
                    handleColTool(obj);
                });
                table.on('colTool(serialSlaveDetail3)', function (obj) {
                    handleColTool(obj);
                });
                table.on('colTool(serialSlaveDetail4)', function (obj) {
                    handleColTool(obj);
                });
                table.on('colTool(serialSlaveDetail6)', function (obj) {
                    handleColTool(obj);
                });
                table.on('colTool(serialSlaveDetail7)', function (obj) {
                    handleColTool(obj);
                });
                // 表头自定义元素工具事件 --- 2.8.8+
                function handleColTool(obj) {
                    var event = obj.event;
                    //console.log(obj);
                    layer.open({
                        type: 1, // page 层类型
                        area: ['50vw', '70vh'],
                        title: '对应接收公式',
                        shade: 0.6, // 遮罩透明度
                        shadeClose: true, // 点击遮罩区域，关闭弹层
                        maxmin: true, // 允许全屏最小化
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        content: `
                        <div class="layui-code-item layui-code-item-preview layui-show" style="">
                            <div class="layui-panel">
                                <div style="padding: 32px;">
                                    <h3 style="padding: 5px;">表达式:</h3>
                                    <li style="padding: 5px;">只能用+-*/()进行运算，[]用来选取点位,[1]代表ID:1的采集点的值 比如:([1]+[2]/2)*10</li>
                                </div>
                            </div>
                        </div>
                        <div class="layui-code-item layui-code-item-preview layui-show" style="">
                            <div class="layui-panel">
                             <div style="padding: 32px;">
                                <h3 style="padding: 5px;">C#接收公式：</h3>
                                <li style="padding: 5px;">位读取： Convert.ToInt16(E1,16)</li>
                                <li style="padding: 5px;"> 8位无符号： Convert.ToInt16(E1,16)</li>
                                <li style="padding: 5px;">16位有符号： Convert.ToInt16(E1,16)</li>
                                <li style="padding: 5px;">16位无符号： Convert.ToUInt16(E1,16)</li>
                                <li style="padding: 5px;">32位有符号： Convert.ToInt32(E1+E2,16)</li>
                                <li style="padding: 5px;">32位无符号： Convert.ToUInt32(E1+E2,16)</li>
                                <li style="padding: 5px;">64位有符号： Convert.ToInt64(E1+E2+E3,16)</li>
                                <li style="padding: 5px;">64位无符号： Convert.ToUInt64(E1+E2+E3+E4,16)</li>
                                <li style="padding: 5px;">32位浮点数： BitConverter.ToSingle(BitConverter.GetBytes(Convert.ToUInt32(E1+E2,16)), 0)</li>
                                <li style="padding: 5px;">64位浮点数： BitConverter.ToDouble(BitConverter.GetBytes(Convert.ToUInt64(E1+E2+E3+E4,16)), 0)</li>
                                </div>
                            </div>
                        </div>`
                    });
                };
                //console.log("options", options)
                // 初始化时给 select 赋值
                form.val('demo-form', {
                    'CJ188Type': options.CJ188Type == undefined ? "10" : options.CJ188Type,
                    'CJ188DataIdentifier': options.CJ188DataIdentifier == undefined ? "1F90" : options.CJ188DataIdentifier,
                    'CJ188UnitType': options.CJ188UnitType == undefined ? 2 : options.CJ188UnitType,
                    'ModbusType': options.ModbusType == undefined ? 1 : options.ModbusType,
                    'IsCollect': options.IsCollect == undefined ? 1 : options.IsCollect,

                });
                // select 事件              
                // form.on('select(dataC)', function (data) {
                //     // console.log('data', data)
                //     var elem = data.elem; // 获得 select 原始 DOM 对象
                //     var value = data.value; // 获得被选中的值
                //     var dtestValue = elem.getAttribute('lay-options');
                //     var prevValue = elem.getAttribute('prevValue') //上次的value

                //     if (prevValue != null) {
                //         if (prevValue != value) {
                //             //同一个不变化
                //             var dataS = collectDataSelect(prevValue, value, $('#collectData' + dtestValue).text())
                //             $("#collectData" + dtestValue).html(dataS)
                //         }
                //     } else {
                //         //值类型
                //         if (value != "0") {
                //             var dataS = collectDataSelect(prevValue, value, $('#collectData' + dtestValue).text())
                //             $("#collectData" + dtestValue).html(dataS)

                //         }

                //     }
                //     // 将当前的 value 存储为之前的 value
                //     elem.setAttribute('prevValue', value);

                // });
                //提交地址位
                form.on('submit(submit2)', function (data) {
                    var field = data.field; // 获取表单字段值
                    // 显示填写结果，仅作演示用
                    field.Serial_ID = parseInt(options.Serial_ID)
                    field.ID = parseInt(options.Serial_Slave_ID)
                    field.CJ188UnitType = parseInt(field.CJ188UnitType)
                    field.ModbusType = parseInt(field.ModbusType)
                    field.IsCollect = parseInt(field.IsCollect)

                    var obj = { SerialSlave: field }
                    EditSeriaSlave(obj).then(function (responseData1) {
                        if (responseData1.success) {
                            form1()
                        } else {
                            return false
                        }
                    })
                    // location.reload();
                    return false; // 阻止默认 form 跳转
                });
                //删除地址位
                form.on('submit(submitdelete)', function (data) {
                    layer.confirm('确认删除数据吗', function (index) {
                        const postData = { serialSlaveID: parseInt(options.Serial_Slave_ID) };
                        DeleteSeriaSlave(postData).then(function (responseData1) {
                            form1()
                            $('#right-form').empty();
                        })
                    });
                    return false; // 阻止默认 form 跳转
                });
                //导出数据
                form.on('submit(submitExport)', function (data) {
                    //console.log("data", data)
                    // 提交表单以触发下载
                    document.getElementById("exportForm").submit();
                    return false; // 阻止默认 form 跳转
                });
                var obj = { Serial_ID: serial_ID, Serial_Slave_ID: serial_Slave_ID, Types: 1 }
                var objs = JSON.stringify(obj)
                var item = { UplaodDatas: objs }
                var obj2 = { Serial_ID: serial_ID, Serial_Slave_ID: serial_Slave_ID, Types: 2 }
                var objs2 = JSON.stringify(obj2)
                var item2 = { UplaodDatas: objs2 }
                // 导入数据
                upload.render({
                    elem: '#uploadBtn',
                    url: '/Serial/UplaodData',  // 后端处理文件上传的接口地址
                    data: item,
                    done: function (res) {

                        layer.msg("导入成功");
                        $('#right-form').empty();
                        form1()
                        // var elem = tableConfigs[1].elem
                        // var configoptions = tableConfigs[1].options;
                        // console.log("elem", elem)
                        // console.log("configoptions", configoptions)
                        // console.log("tableConfigs", tableConfigs)
                        // table.reload(elem.substring(1), configoptions, true);

                    },
                    error: function () {
                        // 上传出错时的回调函数
                        layer.msg("导入失败", {
                            icon: 2
                        });
                    }
                });
                upload.render({
                    elem: '#uploadBtn2',
                    url: '/Serial/UplaodData',  // 后端处理文件上传的接口地址
                    data: item2,
                    done: function (res) {
                        layer.msg("导入成功");
                        $('#right-form').empty();
                        form1()
                    },
                    error: function () {
                        // 上传出错时的回调函数
                        layer.msg("导入失败", {
                            icon: 2
                        });
                    }
                });

                var tableConfigs = [
                    {
                        elem: '#serialSlaveDetail1',
                        options: options1,
                        dataList: dataList1,
                        type: 1
                    },
                    {
                        elem: '#serialSlaveDetail2',
                        options: options2,
                        dataList: dataList2,
                        type: 2
                    },
                    {
                        elem: '#serialSlaveDetail3',
                        options: options3,
                        dataList: dataList3,
                        type: 3
                    },
                    {
                        elem: '#serialSlaveDetail4',
                        options: options4,
                        dataList: dataList4,
                        type: 4
                    },
                    {
                        elem: '#serialSlaveDetail5',
                        options: options5,
                        dataList: dataList5,
                        type: 0
                    },
                    {
                        elem: '#serialSlaveDetail6',
                        options: options6,
                        dataList: dataList6,
                        type: 10
                    },
                    {
                        elem: '#serialSlaveDetail7',
                        options: options7,
                        dataList: dataList7,
                        type: 11
                    }
                ];

                tableConfigs.forEach(function (config) {
                    var elem = config.elem;
                    var configoptions = config.options;
                    var configdataList = config.dataList;
                    var configdtype = config.type;
                    table.render(configoptions);
                    // form.render()
                    form.render('select'); // 仅渲染 select 元素
                    form.on('select(modbusValueType)', function (data) {
                        var elem = data.elem; // 获得 select 原始 DOM 对象
                        var value = data.value; // 获得被选中的值
                        var sid = parseInt(elem.getAttribute('sid'))
                        var type = parseInt(elem.getAttribute('type'))
                        var dataList = dataList3
                        var options = options3
                        if (type == 4) {
                            dataList = dataList4
                            options = options4
                        }
                        dataList.forEach(cd => {
                            if (cd.ID === sid) {
                                cd.ValueType = parseInt(value)
                            }
                        });
                        table.render(options);
                        form.render('select'); // 仅渲染 select 元素
                    });
                    table.on('tool(' + elem.substring(1) + ')', function (obj) {
                        var dataobj = obj.data; // 获得当前行数据
                        console.log("dataobj", dataobj)
                        if (obj.event === 'detailSave') {
                            // 保存操作
                            if (dataobj.CollectAddressID === '') {
                                layer.msg("寄存器地址必填", {
                                    icon: 2
                                });
                                return false;
                            }
                            // console.log('options', options)
                            if (options.Agreement == "1" || options.Agreement == "4" || options.Agreement == "5") {
                                if ($("#ValueType" + dataobj.ID).val() == "" || $("#ValueType" + dataobj.ID).val() == undefined) {
                                    layer.msg("ID:" + dataobj.ID + "的数据类型未选择", {
                                        icon: 2
                                    });
                                    return false;
                                }
                                dataobj.ValueType = parseInt($("#ValueType" + dataobj.ID).val())
                                if (options.Agreement == "1" || options.Agreement == "4") {
                                    if (dataobj.ValueType == 4 || dataobj.ValueType == 3 || dataobj.ValueType == 5 ||
                                        dataobj.ValueType == 6 || dataobj.ValueType == 12 || dataobj.ValueType == 7 || dataobj.ValueType == 8) {
                                        if ($("#ValueStructure" + dataobj.ID).val() == "" || $("#ValueStructure" + dataobj.ID).val() == undefined) {
                                            layer.msg("ID:" + dataobj.ID + "的数据结构未选择", {
                                                icon: 2
                                            });
                                            return false;
                                        }
                                    }
                                    dataobj.ValueStructure = parseInt($("#ValueStructure" + dataobj.ID).val())
                                }
                            }
                            if (dataobj.Type == 0) { //dlt645
                                if (dataobj.DI3 == "" || dataobj.DI3 == undefined || dataobj.DI3.length > 2) {
                                    layer.msg("DI3必填，且不超过两位", {
                                        icon: 2
                                    });
                                    return false;
                                } else if (dataobj.DI3.length == 1) {
                                    dataobj.DI3 = "0" + dataobj.DI3
                                }
                                if (dataobj.DI2 == "" || dataobj.DI2 == undefined || dataobj.DI2.length > 2) {
                                    layer.msg("DI2必填，且不超过两位", {
                                        icon: 2
                                    });
                                    return false;
                                } else if (dataobj.DI2.length == 1) {
                                    dataobj.DI2 = "0" + dataobj.DI2
                                }
                                if (dataobj.DI1 == "" || dataobj.DI1 == undefined || dataobj.DI1.length > 2) {
                                    layer.msg("DI1必填，且不超过两位", {
                                        icon: 2
                                    });
                                    return false;
                                } else if (dataobj.DI1.length == 1) {
                                    dataobj.DI1 = "0" + dataobj.DI1
                                }
                                if (dataobj.DI0 == "" || dataobj.DI0 == undefined || dataobj.DI0.length > 2) {
                                    layer.msg("DI0必填，且不超过两位", {
                                        icon: 2
                                    });
                                    return false;
                                } else if (dataobj.DI0.length == 1) {
                                    dataobj.DI0 = "0" + dataobj.DI0
                                }
                                dataobj.Code = dataobj.DI3 + "," + dataobj.DI2 + "," + dataobj.DI1 + "," + dataobj.DI0
                            }
                            if (dataobj.Type == 10) {//西门子s7协议
                                if ($("#ValueType" + dataobj.ID).val() == "" || $("#ValueType" + dataobj.ID).val() == undefined) {
                                    layer.msg("ID:" + dataobj.ID + "的数据类型未选择", {
                                        icon: 2
                                    });
                                    return false;
                                }
                                dataobj.ValueType = parseInt($("#ValueType" + dataobj.ID).val())
                                if ($("#SiemensType" + dataobj.ID).val() == "" || $("#SiemensType" + dataobj.ID).val() == undefined) {
                                    layer.msg("ID:" + dataobj.ID + "的通道类型未选择", {
                                        icon: 2
                                    });
                                    return false;
                                }
                                dataobj.SiemensType = parseInt($("#SiemensType" + dataobj.ID).val())
                                if (dataobj.SiemensAdress == "" || dataobj.SiemensAdress == undefined) {
                                    layer.msg("ID:" + dataobj.ID + "地址必填", {
                                        icon: 2
                                    });
                                    return false;
                                }
                                if (dataobj.SiemensType == 4) { //通道类型DB
                                    if (dataobj.SiemensAdress.indexOf('.') == -1) {
                                        //不包含.
                                        layer.msg("ID:" + dataobj.ID + "通道类型为DB时，地址位必须包含小数点，格式如：100.1", {
                                            icon: 2
                                        });
                                        return false;
                                    }
                                } else {
                                    if (dataobj.SiemensAdress.indexOf('.') !== -1) {
                                        //不包含.
                                        layer.msg("ID:" + dataobj.ID + "通道类型非DB时，地址位必须正整数，不能包含小数点", {
                                            icon: 2
                                        });
                                        return false;
                                    }
                                }
                            }
                            if (dataobj.Type == 11) {//cj188
                                if (dataobj.CJ188DecimalPointOffset == null) {
                                    dataobj.CJ188DecimalPointOffset = 0
                                }
                                if (dataobj.CJ188DecimalPointOffset < 0 || dataobj.CJ188DecimalPointOffset > 8) {
                                    layer.msg("ID:" + dataobj.ID + "小数点偏移位数范围:0~8", {
                                        icon: 2
                                    });
                                    return false
                                }
                                dataobj.CJ188DecimalPointOffset = parseInt(dataobj.CJ188DecimalPointOffset)
                                dataobj.CJ188CType = parseInt($("#CJ188CType" + dataobj.ID).val())

                            }
                            dataobj.CollectAddressID = parseInt(dataobj.CollectAddressID)
                            if (dataobj.ValueType == -1) {
                                //表达式
                                if (dataobj.Formula == "" || dataobj.Formula == undefined ||  dataobj.Formula =="null") {
                                    layer.msg("ID:" + dataobj.ID + "数据类型为表达式，表达式公式必须填写", {
                                        icon: 2
                                    });
                                    return false
                                }
                            } else {
                                // if (dataobj.Formula != "" && dataobj.Formula != undefined &&dataobj.Formula != "null") {
                                //     layer.msg("ID:" + dataobj.ID + "数据类型不为表达式，表达式公式不能填写", {
                                //         icon: 2
                                //     });
                                //     return false
                                // }                               
                                dataobj.Formula=""
                                
                            }
                            var postData = { SerialSlaveDetail: dataobj };

                            EidtSeriaSlaveDetail(postData).then(function (responseData1) {
                                //console.log('responseData1', responseData1)
                                if (responseData1.code == 0) {
                                    GetSerialInfo().then(function (responseData) {
                                        data = responseData;
                                        var dataList = [];
                                        processData(data, configdtype, dataList);
                                        configdataList.splice(0, configdataList.length, ...dataList);
                                        table.reload(elem.substring(1), configoptions, true);
                                    });
                                }
                            });
                        } else if (obj.event === 'delete') {
                            // 删除操作
                            const postData = { serialSlaveDetailID: dataobj.ID };
                            if (dataobj.ID == 0) {
                                //如果删除的是新增的空行
                                obj.del();
                                configdataList.pop() //删除最后一个空元素
                            }
                            else {
                                DeleteSlaveDetail(postData).then(function (deleteresponseData) {
                                    if (deleteresponseData.code == 0) {
                                        GetSerialInfo().then(function (responseData) {
                                            data = responseData;
                                            var dataList = [];
                                            processData(data, configdtype, dataList);
                                            configdataList.splice(0, configdataList.length, ...dataList);
                                            table.reload(elem.substring(1), configoptions, true);
                                        });
                                    }
                                })
                            }
                        }
                    });
                    //工具栏事件
                    table.on('toolbar(' + elem.substring(1) + ')', function (obj) {
                        // console.log('obj', obj)
                        var id = obj.config.id;
                        var checkStatus = table.checkStatus(id);
                        switch (obj.event) {
                            case 'add':
                                var name = ""
                                var i = 0
                                if (elem.substring(1) === "serialSlaveDetail1") {
                                    name = "F1_YC"
                                } else if (elem.substring(1) === "serialSlaveDetail2") {
                                    name = "F2_YC"
                                } else if (elem.substring(1) === "serialSlaveDetail3") {
                                    name = "F3_YC"
                                } else if (elem.substring(1) === "serialSlaveDetail4") {
                                    name = "F4_YC"
                                } else if (elem.substring(1) === "serialSlaveDetail5") {
                                    name = "YC"
                                } else if (elem.substring(1) === "serialSlaveDetail6") {
                                    name = "YC"
                                } else if (elem.substring(1) === "serialSlaveDetail7") {
                                    name = "YC"
                                }

                                configdataList.forEach(c => {
                                    if (c.Name.indexOf(name) != -1) {
                                        //存在F1_YC 
                                        i++
                                    }
                                });
                                name = name + i

                                var dataCopy = {
                                    CollectName: '',
                                    Name: name,
                                    Describe: '',
                                    CollectAddressID: '0',
                                    ID: 0,
                                    Serial_ID: parseInt(options.Serial_ID),
                                    Serial_Slave_ID: parseInt(options.Serial_Slave_ID),
                                    Type: configdtype
                                };

                                configdataList.push(dataCopy);
                                table.reload(elem.substring(1), configoptions, true);
                                break;
                            case 'deletes':

                                var data = checkStatus.data;
                                if (data.length === 0) {
                                    table.reload(elem.substring(1), configoptions, true);
                                    return layer.msg('请选择一行');
                                }

                                var ids = "";
                                data.forEach((element, index) => {
                                    ids += element.ID.toString();

                                    if (index < data.length - 1) {
                                        ids += ",";
                                    }
                                });
                                if (ids != "") {
                                    const postData = { serialSlaveDetailID: ids };
                                    DeleteSlaveDetail(postData).then(function (deleteresponseData) {
                                        if (deleteresponseData.code == 0) {
                                            GetSerialInfo().then(function (responseData) {
                                                data = responseData;
                                                var dataList = [];
                                                processData(data, configdtype, dataList);
                                                configdataList.splice(0, configdataList.length, ...dataList);
                                                table.reload(elem.substring(1), configoptions, true);
                                            });
                                        }
                                    })
                                }

                                table.reload(elem.substring(1), configoptions, true);
                                break;
                        };
                    })
                    table.on('edit(' + elem.substring(1) + ')', function (obj) {
                        var field = obj.field; // 得到修改的字段
                        var value = obj.value // 得到修改后的值
                        var oldValue = obj.oldValue // 得到修改前的值 -- v2.8.0 新增
                        var data = obj.data // 得到所在行所有键值
                        var col = obj.getCol(); // 得到当前列的表头配置属性 -- v2.8.0 新增
                        // console.log('obj', obj)
                        //  console.log('col', col)
                        // 值的校验
                        if (field != 'Describe' && field != 'Formula' && value.replace(/\s/g, '') === '') {
                            layer.tips('值不能为空', this, { tips: 1 });
                            return obj.reedit(); // 重新编辑 -- v2.8.0 新增
                        } else if (field == "CollectAddressID" || field == "DI3" || field == "DI2" || field == "DI1" || field == "DI0" || field == "CJ188DecimalPointOffset") {
                            var tegexPort = /^[0-9]\d*$/;
                            if (!(tegexPort.test(value))) {
                                layer.tips('只能填写数字', this, { tips: 1 });
                                return obj.reedit();
                            }
                            if (field == "CJ188DecimalPointOffset") {
                                if (value < 0 || value > 8) {
                                    layer.tips(' 小数点偏移位数范围:0~8', this, { tips: 1 });
                                    return obj.reedit();
                                }
                            }
                        } else if (field == "SiemensAdress") {
                            var tegexPort = /^[0-9]+(\.[0-9]+)?$/;
                            if (!(tegexPort.test(value))) {
                                layer.tips('只能填写数字或小数', this, { tips: 1 });
                                return obj.reedit();
                            }
                        } else if (field == "Formula") {
                            if (value != "") {
                                var tegexPort = /^[0-9+\-*/()\[\]]+$/;
                                if (!(tegexPort.test(value))) {
                                    layer.tips('只能填写数字和+-*/()[]', this, { tips: 1 });
                                    return obj.reedit();
                                }
                            }
                        }
                        // $('#detailSave').css("display", "inline-block");
                        // 显示 - 仅用于演示

                        //layer.msg('[ID: ' + data.ID + '] ' + field + ' 字段更改值为：' + util.escape(value));
                    });
                });
                element.on('tab(tab-hash)', function (data) {
                    if (data.index == 0) {
                        $("#button2").css("display", "inline-block");
                        $("#buttonDelete").css("display", "inline-block");
                    } else {
                        var elem = tableConfigs[data.index - 1].elem
                        var configoptions = tableConfigs[data.index - 1].options;
                        table.reload(elem.substring(1), configoptions, true);
                        $("#button2").css("display", "none");
                        $("#buttonDelete").css("display", "none");
                    }
                })
                // });
            }
            function form3(options) {
                // console.log('options', options)

                //点击地址位
                // 遍历数据，动态生成菜单项
                var html = '';
                // data.forEach(function (item) {
                html += `  <div class="layui-card-header"><h3>新建设备</h3><span> <button class="layui-btn layui-btn-primary layui-border-green" lay-submit  lay-filter="submit3">提交</button></span></div> 
                <div class="layui-tab" lay-filter="tab-hash">
                    <ul class="layui-tab-title">
                      <li class="layui-this" lay-id="0">基本信息</li>
                    </ul>
                    
                    <div class="layui-tab-content">
                      <div class="layui-tab-item layui-show">
                        <div class="layui-card-body">
    <li class="layui-menu  layui-menu-item-divider"></li>
    <div class="layui-form-item topinput">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input type="text" name="Name" autocomplete="off" placeholder="请输入" lay-verify="required"
                 class="layui-input">
        </div>
    </div>
    <div class="layui-form-item topinput">
        <label class="layui-form-label">描述</label>
        <div class="layui-input-block">
            <input type="text" name="Describe" autocomplete="off" placeholder="请输入" 
               class="layui-input">
            <input name="ID" style="display:none">
        </div>
    </div>
    <div class="layui-form-item topinput ${options.Agreement == "5" ? "" : 'layui-hide'}">
        <label class="layui-form-label">仪表类型</label>
        <div id="CJ188Type" class="layui-input-block">
            <select name="CJ188Type">
                <option value="10"selected>冷水水表</option>
                <option value="11">生活热水水表</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item topinput ${options.Agreement == "5" ? "" : 'layui-hide'}">
        <label class="layui-form-label">数据标识</label>
        <div id="CJ188DataIdentifier" class="layui-input-block">
            <select name="CJ188DataIdentifier">
                <option value="1F90"selected>1F90</option>
                <option value="901F">901F</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item topinput ${options.Agreement == "5" ? "" : 'layui-hide'}">
        <label class="layui-form-label">单位位置</label>
        <div id="CJ188UnitType" class="layui-input-block">
            <select name="CJ188UnitType">
                <option value=1>在前</option>
                <option value=2 selected>在后面</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item topinput">
        <label class="layui-form-label">设备地址</label>
        <div class="layui-input-block">
            <input type="number" lay-affix="number"  name="ModbusSlaveID" autocomplete="off" placeholder="请输入" lay-verify="required"
                class="layui-input">
            <input name="ID" style="display:none">
        </div>
    </div>
    <div class="layui-form-item topinput ${options.Agreement == "1" ? "" : 'layui-hide'}">
        <label class="layui-form-label">单位位置</label>
        <div id="ModbusType" class="layui-input-block">
            <select name="ModbusType">
                <option value=1 selected>单点采集</option>
                <option value=2 >整帧采集</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item topinput">
        <label class="layui-form-label">是否采集</label>
        <div id="IsCollect" class="layui-input-block">
            <select name="IsCollect">
                <option value=1 selected>采集</option>
                <option value=2 >不采集</option>
            </select>
        </div>
    </div>
    
</div>
                        </div>
                    </div>
                  </div>`
                // });
                $('#right-form').append(html);
                form.render();
                // 提交事件
                form.on('submit(submit3)', function (data) {
                    var field = data.field; // 获取表单字段值
                    field.Serial_ID = parseInt(options.Serial_ID)
                    field.ID = 0
                    field.CJ188UnitType = parseInt(field.CJ188UnitType)
                    field.ModbusType = parseInt(field.ModbusType)
                    field.IsCollect = parseInt(field.IsCollect)

                    var obj = { SerialSlave: field }
                    EditSeriaSlave(obj).then(function (responseData1) {
                        if (responseData1.success) {
                            form1()
                        } else {
                            return false
                        }
                    })

                    // location.reload();
                    return false; // 阻止默认 form 跳转
                });
                //  })
            }
            function form4(data) {
                var html = '';
                html += `
                            <div class="layui-card-header"><h3>采集周期配置</h3>
                                <span> <button class="layui-btn layui-btn-primary layui-border-green" lay-submit  lay-filter="TPITVsubmit">提交</button></span>
                            </div>
                            <div class="layui-card-body">
                                <li class="layui-menu  layui-menu-item-divider"></li>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label">采集周期(秒)</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="1" name="TPITV" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"   value='${data.TPITV}' >                                        
                                            <input name="ID" value=${data.ID}  style="display:none">
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label">超时时间(秒)</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="1" max="5" name="Timeout" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"   value='${data.Timeout}' >                                        
                                            <input name="ID" value=${data.ID}  style="display:none">
                                    </div>
                                </div>
                                <div class="layui-form-item topinput">
                                    <label class="layui-form-label">重试次数</label>
                                    <div class="layui-input-block">
                                        <input type="number" min="1" max="5" name="RetryCount" autocomplete="off" placeholder="请输入" lay-verify="required" lay-affix="number"
                                        onkeyup="value=value.replace(/[^\\d]/g,'')"  class="layui-input"   value='${data.RetryCount}' >                                        
                                            <input name="ID" value=${data.ID}  style="display:none">
                                    </div>
                                </div>
                            </div>`
                $('#right-form').append(html);
                form.render(); // 渲染全部表单
                //提交 （已废弃
                form.on('submit(TPITVsubmit)', function (data) {
                    var field = data.field; // 获取表单字段值
                    field.TPITV = parseInt(field.TPITV)
                    field.Timeout = parseInt(field.Timeout)
                    field.RetryCount = parseInt(field.RetryCount)
                    field.ID = parseInt(field.ID)
                    if (field.TPITV < 0 || field.TPITV == 0) {
                        layer.msg("采集周期必须大于0", {
                            icon: 2
                        });
                        return false;
                    }
                    if (field.Timeout <= 0 || field.Timeout > 5) {
                        layer.msg("超时时间范围1~5", {
                            icon: 2
                        });
                        return false;
                    }
                    if (field.RetryCount <= 0 || field.RetryCount > 5) {
                        layer.msg("重试次数范围1~5", {
                            icon: 2
                        });
                        return false;
                    }
                    var obj = { TPITV: (field) }
                    EidtTPITV(obj)
                    // location.reload();
                    return false; // 阻止默认 form 跳转
                });
            }
            var popups = true; //弹窗是可以开启 true：可以
            const hostname = window.location.hostname
            const port = window.location.port
            ws = new WebSocket('ws://' + hostname + ':' + port + '/Websocket/Serial/ws');
            ws.binaryType = 'arraybuffer'; // "blob";//
            var lock = true;
            ws.onmessage = (msg) => {
                if (lock) {
                    lock = false
                    if (msg != null && msg != undefined && msg.data != null && msg.data != undefined) {
                        var data = JSON.parse(msg.data).Data
                        var type = JSON.parse(msg.data).Type
                        if (data != null && data != undefined && type != null && type != undefined) {
                            if (type == "1") {
                                //采集数据
                                for (var i = 0; i < data.length; i++) {
                                    // console.log("data[i].Value", data[i].ID, data[i].Value)
                                    $("#collectData" + data[i].ID).html(data[i].Value3)
                                    //值类型
                                    // if ($('#collectDataSelect' + data[i].ID).val() != "0") {
                                    //     var dataS = collectDataSelect(0, $('#collectDataSelect' + data[i].ID).val(), data[i].Value)
                                    //     $("#collectData" + data[i].ID).html(dataS)
                                    // }
                                    $("#collectData2_" + data[i].ID).html(data[i].Value2)
                                    $("#collectDataTime" + data[i].ID).html(data[i].CreateTime)
                                }
                            } else if (type == "2") {
                                //错误弹窗
                                // 添加弹窗内容到数组
                                // showNextPopup(data)
                                const nowTimestamp = Math.floor(Date.now() / 1000); //当前时间戳
                                const oldTimestamp = localStorage.getItem("LogTime") //缓存的上次时间
                                if (localStorage.getItem("LogTime") == null) {
                                    showNextPopup("有新的日志信息,请前往查看")
                                    localStorage.setItem("LogTime", nowTimestamp)
                                } else {
                                    // 计算两个时间戳之间的差值（以秒为单位）
                                    const timeDifferenceInSeconds = nowTimestamp - oldTimestamp;

                                    // 计算相差的分钟数
                                    const timeDifferenceInMinutes = Math.floor(timeDifferenceInSeconds / 60);
                                    console.log("timeDifferenceInMinutes", timeDifferenceInMinutes)
                                    if (timeDifferenceInMinutes > 10) {
                                        showNextPopup("有新的日志信息,请前往查看")
                                        localStorage.setItem("LogTime", nowTimestamp)
                                    }

                                }


                            }
                        }
                    }
                    lock = true
                }
                else {
                    console.log("错误进入")
                    // lock = true
                }
            }
            function collectDataSelect(iold, i, data) {
                if (i == 1) {
                    //16进制转10进制的无符号整数
                    var decimalValue = parseInt(data, 16);
                    return decimalValue
                } else if (i == 0) {
                    if (iold == 1) {
                        //十进制转为16进制
                        return decimalToFourDigitHex(parseInt(data))
                    }
                }
            }
            function decimalToFourDigitHex(decimal) {

                if (decimal < 0) {
                    return "0000"; // 负数不适用于此示例
                }

                // 将十进制数转换为十六进制字符串，并在前面添加零
                var hex = decimal.toString(16).toUpperCase();
                while (hex.length < 4) {
                    hex = "0" + hex;
                }

                return hex;
            }
            function showNextPopup(message) {
                var layer = layui.layer;
                var popupOptions = {
                    title: '提示',
                    content: message,
                    shade: 0, // 不显示遮罩
                    // time: 5000, // 显示时间（毫秒）
                    offset: 'rb', // 弹窗位置：右下角
                    end: function () {
                        // 弹窗关闭后触发，从数组中移除当前弹窗
                        popups = true
                    },
                    yes: function (index, layero, that) {
                        // do something
                        popups = true
                        layer.close(index); // 关闭弹层
                        window.location = '../#//page/syslog.html';
                    }
                };
                if (popups) {
                    //已关闭弹窗的才可以再次弹出
                    popups = false
                    var popup = layer.open(popupOptions);
                }
            }
            $('#right-form').on('keydown', function (e) {
                // 判断是否是回车键
                if (e.keyCode === 13) {
                    e.preventDefault(); // 阻止默认行为
                }
            });
        })
    </script>

</body>

</html>